const express = require('express');

const myQuery = require('../tools/database');
let { jwtsuo} = require('../tools/api');
let { jwtSign, jwtVerify } = require('../tools/token');
const http = require('../tools/http');

let router = express.Router();

// 接口
let loginApi = {
    getToken:'/getToken',
    register: '/login/register', // 注册
    getUserList: '/getUserList', // 获取用户列表
    getUserInfoByIds: '/getUserInfoByIds', // 获取用户列表
};

// 融云获取token
router.post(loginApi.getToken, async (req, res, next) => {
    let params = req.body;
    if (!params.name || !params.password) next('参数错误');
    let sql = `SELECT * FROM user WHERE name = '${params.name}' and password = '${params.password}'`;
    let [, result] = await myQuery(sql);

    if (!result.length) {
        let sql1 = `INSERT INTO user (name,password,avatar) VALUES ('${params.name}','${params.password}','https://ts3.cn.mm.bing.net/th?id=OIP-C.y6rdSCGpxbfeb8Rd1CpSuwAAAA&w=250&h=250&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2');`;
        let [err1, result1] = await myQuery(sql1);
    }

    let sql2 = `SELECT * FROM user WHERE name = '${params.name}' and password = '${params.password}'`;
    let [, result2] = await myQuery(sql2);
    

    let token = jwtSign({
        id: result2[0].id,
        name: result2[0].name,
        avatar: result2[0].avatar
    }, jwtsuo, '7h');

    let userInfo = {
        id: result2[0].id,
        name: result2[0].name,
        avatar: result2[0].avatar,
        token
    };
    console.log(result2[0]);
    

   http.post({
        url:'https://api.rong-api.com/user/getToken.json', 
        params:{
            userId:result2[0].id,
            name:result2[0].name,
            portraitUri:result2[0].avatar
        },
    }).then(async (data)=>{     
        console.log(data);
        let sql1 = `INSERT INTO user rc_token VALUES ('${res.data}');`;
        let [err1, result1] = await myQuery(sql1);
        res.send({ code: 1, msg: '登录成功', data: {...userInfo,rc_token: data.token}  });
    }).catch((err)=>{
        res.send({ code: 0, msg: '登录失败', data: err });
    })
    
})


// 获取用户列表
router.post(loginApi.getUserList, async (req, res) => {
    let sql = `SELECT id,name,avatar FROM user`
    let [,result] = await myQuery(sql)
    res.send({code:1,msg:'获取成功',data:result})
})

// 获取用户信息
router.post(loginApi.getUserInfoByIds, async (req, res) => {
    let sql = `SELECT id,name,avatar FROM user WHERE id IN (${req.body.ids})`
    let [,result] = await myQuery(sql)
    res.send({code:1,msg:'获取成功',data:result})
})


module.exports = router;